from flask import render_template, g
from werkzeug.utils import secure_filename
from application import app
from common.models.Image import Image
import os, stat, uuid
import datetime

def ops_render(template, context={}):
    """
    统一渲染模板的方法
    统一渲染模板之后，参数类型由关键字变为字典参数，且包含当前用户的参数
    """
    if 'current_user' in g:
        context['current_user'] = g.current_user
    return render_template(template, **context)

def getCurrentDate(format="%Y-%m-%d %H:%M:%S"):
    """按指定格式生成当前时间"""
    return datetime.datetime.now().strftime(format)

def getFormatDate(date=None, format="%Y-%m-%d %H:%M:%S"):
    """ 生成格式化时间"""
    if not date:
        date = datetime.datetime.now()
    return date.strftime(format)

def SaveImage(upfile):
    """
    上传图片保存功能
    :param upfile:
    :return:
    """
    result = {'code': 200, 'msg': '上传成功', 'data': {}}
    # 获取安全文件名-->secure_filename函数默认过滤中文
    # 需要改动源码，修改正则规则和编码为utf-8
    # filename = secure_filename(upfile.filename)

    filename = upfile.filename
    # 获取文件名扩展
    ext = filename.rsplit('.', 1)[1]
    if ext not in app.config['UPLOAD_IMAGES']['ext']:
        result['code'] = -1
        result['state'] = '上传图片格式错误！'
        return result

    file_config = app.config['UPLOAD_IMAGES']
    # 存储的文件夹以时间命名
    file_dir = getCurrentDate('%Y%m%d')
    file_path = os.path.join(
        app.root_path, file_config['file_root'], file_dir
    )

    if not os.path.exists(file_path):
        os.mkdir(file_path)
        # 修改文件权限为777
        os.chmod(file_path, stat.S_IRWXO | stat.S_IRWXG | stat.S_IRWXU)

    # 使用uuid给上传图片命名
    image_name = str(uuid.uuid4()).replace('-', '') + '.' + ext
    # 图片保存路径
    save_path = os.path.join(file_path, image_name)
    # 保存图片
    upfile.save(save_path)
    # 生成file_key
    file_key = file_dir + '/' + image_name
    result['data'] = {'file_key': file_key}

    # 将file_key保存到数据库
    image = Image()
    image.file_key = file_key
    image.created_time = getCurrentDate()
    image.save()

    return result

# 根据某一个字段，获取它的过滤字典
def getDictFilterFiled(db_model, select_filed, key_filed, id_list):
    ret = {}
    query = db_model.query.filter(db_model.status == 1)
    if id_list and len(id_list) > 0:
        query = query.filter(select_filed.in_(id_list))
    list = query.all()
    for item in list:
        if not hasattr(item, key_filed):
            break
        ret[getattr(item, key_filed)] = item
    return ret

# 根据对象列表获取指定字段的列表
def selectFilterObj(item_list, key_field):
    res = []
    for item in item_list:
        if not hasattr(item, key_field):
            continue
        if getattr(item, key_field) in res:
            continue
        res.append(getattr(item, key_field))
    return res
